package com.ruoyi.web.controller.jjm;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IDCardUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.jjm.domain.*;
import com.ruoyi.jjm.service.*;
import com.ruoyi.jjm.utils.CustomHandler;
import com.ruoyi.jjm.utils.EasyExcelUtil;
import com.ruoyi.jjm.vo.VillageInfo;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/jjm/xiang")
public class XiangController extends BaseController {

    private String prefix = "jjm/xiang";

    @Autowired
    ISysDeptService sysDeptService;

    @Autowired
    IVillageService villageService;

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private IClientUserOrderService clientUserOrderService;

    @Autowired
    private IAreaInfoService areaInfoService;

    @Autowired
    ITownStatisticsService townStatisticsService;

    @Autowired
    IBaolianrenService baolianrenService;
    @Autowired
    ISysDeptService deptService;


    @GetMapping(value = "/info")
    public ModelAndView info(@RequestParam(value = "xiangId",required = false) Long xiangId) {
        SysUser user = ShiroUtils.getSysUser();
        ModelAndView mav = new ModelAndView(prefix + "/info");
        if(xiangId != null){
            mav = new ModelAndView(prefix + "/xiang");
        } else {
            xiangId = user.getDeptId();
        }
        mav.addObject("xiangId",xiangId);
        int alarmCount = clientUserService.selectXiangUninstallAlarmCount(xiangId);
        int noteCount = clientUserService.selectXiangNoNoteCount(xiangId);
        AreaInfo areaInfo = areaInfoService.selectAreaInfoByAreaId(xiangId);
        if(areaInfo == null){
            areaInfo = new AreaInfo();
            areaInfo.setAreaId(xiangId);
        }
        mav.addObject("alarmCount",alarmCount);
        mav.addObject("noteCount",noteCount);
        mav.addObject("areaInfo",areaInfo);
        mav.addObject("dept",sysDeptService.selectDeptById(xiangId));
        mav.addObject("totalAmount",clientUserOrderService.countXiangTotal(xiangId));
        return mav;
    }

    @GetMapping(value = "/mobile")
    public ModelAndView mobile(@RequestParam(value = "id") Long xiangId) {
        ModelAndView mav = new ModelAndView(prefix + "/xiangMobile");
        mav.addObject("xiangId",xiangId);
        SysDept xiangInfo = sysDeptService.selectDeptById(xiangId);
        SysDept xianInfo = sysDeptService.selectDeptById(xiangInfo.getParentId());
        mav.addObject("xiangInfo",xiangInfo);
        mav.addObject("xianInfo",xianInfo);
        mav.addObject("totalAmount",clientUserOrderService.countXiangTotal(xiangId));

        List<SysDept> deptList = deptService.selectDeptByParentId(xiangId);
        mav.addObject("deptList",deptList);
        return mav;
    }
    @GetMapping(value = "/xiang")
    public ModelAndView xiang(@RequestParam(value="xiangId",required = false) Long xiangId) {
        SysUser user = ShiroUtils.getSysUser();
        ModelAndView mav = new ModelAndView(prefix + "/xiang");
        if(xiangId == null){
            xiangId = user.getDeptId();
        } else {
            mav.addObject("xiangId",xiangId);
        }
        int alarmCount = clientUserService.selectXiangUninstallAlarmCount(xiangId);
        int noteCount = clientUserService.selectXiangNoNoteCount(xiangId);
        AreaInfo areaInfo = areaInfoService.selectAreaInfoByAreaId(xiangId);
        if(areaInfo == null){
            areaInfo = new AreaInfo();
            areaInfo.setAreaId(xiangId);
        }
        mav.addObject("alarmCount",alarmCount);
        mav.addObject("noteCount",noteCount);
        mav.addObject("areaInfo",areaInfo);
        mav.addObject("dept",sysDeptService.selectDeptById(xiangId));
        mav.addObject("totalAmount",clientUserOrderService.countXiangTotal(xiangId));
        return mav;
    }

    @PostMapping("/infoTable")
    @ResponseBody
    public TableDataInfo infoTable(@RequestParam(value="xiangId",required = false) Long xiangId) {
        SysUser user = ShiroUtils.getSysUser();
        if(xiangId == null){
            xiangId = user.getDeptId();
        }
        startPage();
        TownStatistics townStatistics = reportData(xiangId);
        List<TownStatistics> tableList = Arrays.asList(townStatistics);
        return getDataTable(tableList);
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value="xiangId",required = false) Long xiangId) {
        SysUser user = ShiroUtils.getSysUser();
        if(xiangId == null){
            xiangId = user.getDeptId();
        }
        startPage();
        List<VillageInfo> tableList = villageList(xiangId);
        return getDataTable(tableList);
    }

    private List<VillageInfo> villageList(Long xiangId){
        List<VillageInfo> tableList = villageService.selectVillageInfoByXiang(xiangId);
        for (VillageInfo village  : tableList) {
            Long orderConfirmed = clientUserOrderService.countOrderConnfirmed(xiangId);
            Long notJjm = village.getJjm() - (orderConfirmed != null?orderConfirmed:0L);
            village.setNotjjm(notJjm);
            village.setOrderAmount(clientUserOrderService.countCunTotal(village.getVillageId()));
            Long baolianHuCount = clientUserService.countVillagePopulation(village.getVillageId());
            village.setBaolianhuCount(baolianHuCount == null ? 0 : baolianHuCount.intValue());
            Long baolianRenCount = baolianrenService.countByAreaId(village.getVillageId());
            village.setBaolianrenCount(baolianRenCount == null ? 0 : baolianRenCount.intValue());
        }
        return tableList;
    }

    @GetMapping("/edit/{id}")
    public ModelAndView villageDetail(@PathVariable(value = "id") Long villageId){
        ModelAndView mav = new ModelAndView(prefix + "/villageDetail");
//        Village village = villageService.selectVillageById(villageId);
        VillageInfo result = villageService.selectVillageInfoByVillageId(villageId);
        double cunTotalOrder = clientUserOrderService.countCunTotal(villageId);
        SysDept dept = sysDeptService.selectDeptById(villageId);
        mav.addObject("dept",dept);
        mav.addObject("user",ShiroUtils.getSysUser());
        mav.addObject("villageId",villageId);
        mav.addObject("cunTotalOrder",cunTotalOrder);
        return mav;
    }

    @GetMapping("/reportData")
    @ResponseBody
    public AjaxResult reportData() {
        SysUser user = ShiroUtils.getSysUser();
        if(user.getDept().getAncestors().split(",").length == 3){
            Long xiangId = user.getDeptId();
            TownStatistics townStatistics = reportData(xiangId);
            townStatisticsService.insertOrUpdateTownStatistics(townStatistics);
        }

        return AjaxResult.success("ok");
    }

    private TownStatistics reportData(Long xiangId){
        SysUser user = ShiroUtils.getSysUser();
        SysDept xiangInfo = deptService.selectDeptById(xiangId);
        SysDept xianInfo = deptService.selectDeptById(xiangInfo.getParentId());
        TownStatistics townStatistics = clientUserService.selectXiangStatisitcsByXiangId(xiangId);
        townStatistics.setTownName(xiangInfo.getDeptName());
        townStatistics.setCountyName(xianInfo.getDeptName());
        Long orderConnfirmed =  clientUserOrderService.countOrderConnfirmed(xiangId);
        townStatistics.setNotCleanCoalNum(townStatistics.getCleanCoalNum() - orderConnfirmed);
        townStatistics.setCountyId(xiangInfo.getParentId());
        townStatistics.setTownId(xiangId);
        townStatistics.setUpdateTime(DateUtils.getNowDate());
        townStatistics.setUpdateBy(user.getLoginName());
        townStatistics.setTotalBuyNum(clientUserOrderService.countXiangTotal(xiangId));
        townStatistics.setVillageBlHouseNum(clientUserService.countBaolianHouseNumByTown(xiangId));
        townStatistics.setVillageBlNum(baolianrenService.countBaolianNumByTown(xiangId));
        VillageInfo villageInfo = villageService.selectVillageInfoByXiangId(xiangId);
        if(villageInfo != null){
            townStatistics.setHouseholdsNum(villageInfo.getResidents());
        }
        AreaInfo countyInfo = areaInfoService.selectAreaInfoByAreaId(xiangId);
        if (countyInfo != null) {
            townStatistics.setTownBlNum(countyInfo.getBaolianCadreNum());
            townStatistics.setTownBlVillageNum(countyInfo.getBaolianAreaNum());
        }
        return townStatistics;
    }

    @RequestMapping("/detail")
    public ModelAndView detail(@RequestParam(value = "page") String page,
                               @RequestParam(value="xiangId",required = false) Long xiangId) {
        ModelAndView mav = new ModelAndView(prefix + "/detail");
        mav.addObject("page",page);
        mav.addObject("xiangId",xiangId);
        return mav;
    }

    @PostMapping("/detailList")
    @ResponseBody
    public TableDataInfo detailList(@RequestParam(value = "page") String page,
                                    @RequestParam(value="xiangId",required = false) Long xiangId) {
        SysUser user = ShiroUtils.getSysUser();
        if(xiangId == null){
            xiangId = user.getDeptId();
        }
        startPage();
        List<ClientUser> result = new ArrayList<>();
        if(page.equals("alarm")){
            result = clientUserService.selectXiangUnistallAlarmList(xiangId);
        } else if(page.equals("note")) {
            result = clientUserService.selectXiangNoNoteList(xiangId);
        }
        return getDataTable(result);
    }

    /**
     * 信息录入页面
     * @return
     */
    @GetMapping("/infoInput")
    public ModelAndView dataInput() {
        ModelAndView mav = new ModelAndView(prefix + "/infoInput");
        return mav;
    }

    /**
     * 信息录入页面
     * @return
     */
    @PostMapping("/infoInputList")
    @ResponseBody
    public TableDataInfo infoInputList() {
        SysUser user = ShiroUtils.getSysUser();
        SysDept queryParams = new SysDept();
        queryParams.setParentId(user.getDeptId());
        List<SysDept> result = sysDeptService.selectDeptList(queryParams);
        return getDataTable(result);
    }


    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam(value = "townId",required = false) Long townId) throws InvocationTargetException, IllegalAccessException {
        SysUser user = ShiroUtils.getSysUser();
        SysDept dept = user.getDept();
        if(townId == null){
            townId = user.getDeptId();
        }

        dept = deptService.selectDeptById(townId);
        TownStatistics query = new TownStatistics();
        query.setTownId(townId);
        List<TownStatistics> list = townStatisticsService.selectTownStatisticsList(query);
        if(CollectionUtils.isEmpty(list)){
            return AjaxResult.warn("居民户籍信息为空");
        }
        List<TownStatisticsTable> tableList = new ArrayList<>();
        for(TownStatistics statistics : list){
            TownStatisticsTable table = new TownStatisticsTable(statistics);
            tableList.add(table);
        }
        String fileName = dept.getDeptName()+"居民户籍信息" + System.currentTimeMillis() + ".xlsx";

        EasyExcel.write(Global.getDownloadPath()+fileName, TownStatisticsTable.class)
                .needHead(true)
                .head(TownStatisticsTable.class)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new CustomHandler())
                .registerWriteHandler(EasyExcelUtil.getStyleStrategy()).sheet("居民户籍信息").doWrite(tableList);
        return AjaxResult.success(fileName);
    }
    @PostMapping("/exportXiang")
    @ResponseBody
    public AjaxResult exportXiang(@RequestParam(value = "townId",required = false) Long townId)
    {
        SysUser user = ShiroUtils.getSysUser();
        SysDept dept = user.getDept();
        if(townId == null){
            townId = dept.getDeptId();
        }
        dept = deptService.selectDeptById(townId);
        List<VillageInfo> tableList =villageList(townId);

        String fileName = dept.getDeptName()+"居民户籍信息" + System.currentTimeMillis() + ".xlsx";

        EasyExcel.write(Global.getDownloadPath()+fileName, VillageInfo.class)
                .needHead(true)
                .head(VillageInfo.class)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new CustomHandler())
                .registerWriteHandler(EasyExcelUtil.getStyleStrategy()).sheet("居民户籍信息").doWrite(tableList);
        return AjaxResult.success(fileName);
    }
}
